<?php
include_once("_common.php");
include_once("$g4[path]/head.sub.php");

$mb_id = $member['mb_id'];

set_session("cash_contents", '');
set_session("cash_membership", '');
set_session("download_membership", '');

$lst = array();
if ($bo_table) {
    include_once("$board_skin_path/mw.lib/mw.skin.basic.lib.php");

    $is_membership = false;

    $sql = " select * from $mw_cash[membership_board_table] where bo_table = '$bo_table' ";
    $qry = sql_query($sql);
    while ($row = sql_fetch_array($qry)) {
        $lst[] = $row[ms_id];
    }

    $lst = implode("','", $lst);
    $sql = " select * from $mw_cash[membership_table] where ms_id in ('$lst') and ms_status = '1' ";
    $qry = sql_query($sql);
    while ($row = sql_fetch_array($qry)) {
        if (sql_fetch(" select * from $mw_cash[membership_item_table] where ms_id = '$row[ms_id]' and mi_status = '1' ")) {
            $is_membership = true;
            break;
        }
    }
    if (!$is_membership) {
        if ($mw_basic[cf_not_membership_msg]) {
            $msg = trim(addslashes($mw_basic[cf_not_membership_msg]));
            $url = trim(addslashes($mw_basic[cf_not_membership_url]));
            echo "<script>alert(\"{$msg}\");</script>";
            if ($url)
                echo "<script>opener.location.href=\"{$url}\"; self.close();</script>";
            exit;
        }
        else {
            alert_close("현재 가입을 받고 있지 않습니다.");
        }
    }
}

$list = array();
$rows = array();

$z = 0;
$sql = " select * from $mw_cash[membership_item_table] i, $mw_cash[membership_table] m ";
$sql.= " where i.ms_id = m.ms_id ";
$sql.= " and m.ms_status = '1' ";
$sql.= " and i.mi_status = '1' ";

if ($bo_table && $lst && $mw_cash[cf_membership_board_list] == 'b') {
    $sql.= " and i.ms_id in ('$lst') ";
}
$sql.= " order by i.ms_id, i.mi_cash desc  ";
$qry = sql_query($sql);
for ($i=0; $row=sql_fetch_array($qry); $i++) {
    $cash = $row[mi_cash];
    $is_extend = false;
    $is_join_sale = false;

    $sq2 = " select * from $mw_cash[membership_log_table] where mb_id = '$mb_id' and ms_id = '$row[ms_id]' ";
    $ro2 = sql_fetch($sq2);
    if ($ro2)
        $is_new = 're';
    else
        $is_new = 'new';

    if ($row[mi_renew]) {
        $tmp = sql_fetch(" select * from $mw_cash[membership_log_table] where mb_id = '$mb_id' and ms_id = '$row[ms_id]' and ml_edate > '$g4[time_ymdhis]' ");
        if (!$tmp) continue;
    }

    $sq2 = " select * from $mw_cash[membership_log_table] where mb_id = '$mb_id' and ml_edate > '$g4[time_ymdhis]' and ms_id = '$row[ms_id]' ";
    $ro2 = sql_fetch($sq2);
    if ($ro2) {
        if ($row[mi_cash_extend])
            $cash = round($cash*(100-$row[mi_cash_extend])/100);
        $is_extend = true;
    }

    // 장기회원 할인
    if ($row[mi_cash_join_day] && $row[mi_cash_join_day] < ($g4[server_time]-strtotime($member[mb_datetime]))/(60*60*24)) {
        if (!$is_extend or $row[mi_cash_extend] < $row[mi_cash_join_sale]) {
            $cash = round($row[mi_cash]*(100-$row[mi_cash_join_sale])/100);
            $is_join_sale = true;
            $is_extend = false;
        }
    }

    $rows[$row[ms_id]]++;

    $list[$z] = $row;
    $list[$z][cash] = $cash;
    $list[$z][is_extend] = $is_extend;
    $list[$z][is_join_sale] = $is_join_sale;
    $list[$z][ml_edate] = $ro2[ml_edate];
    $list[$z][is_new] = $is_new;
    $z++;
}
?>
<link rel="stylesheet" href="./buy-membership-style.css" type="text/css"/>

<div id="box">

<form name="fwrite" method="post" action="<?=$mw_cash[path]?>/cash-charge-update.php">
<input type="hidden" name="paytype" value="">
<input type="hidden" name="membership" value="1">
<input type="hidden" name="ac_cash" value="1">

<h3>멤버쉽 가입</h3>
<? echo $mw_cash[cf_membership_head]; ?>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="t">
<colgroup width="100"/>
<colgroup width=""/>
<colgroup width="150"/>
<colgroup width="230"/>
<colgroup width="100"/>
<tr>
    <td class="tt">멤버쉽</td>
    <td class="tt">
        <input type="checkbox" checked onclick="all_check(this); set_total_cash();"/>
        상품
    </td>
    <td class="tt"><?=$mw_cash[cf_cash_name]?></td>
    <td class="tt">정보</td>
    <td class="tt">결제금액</td>
</tr>
<?
/*
$sql = " select * from $mw_cash[membership_item_table] i, $mw_cash[membership_table] m ";
$sql.= " where i.ms_id = m.ms_id ";
$sql.= " and m.ms_status = '1' ";
$sql.= " and i.mi_status = '1' ";
$sql.= " order by i.mi_cash desc ";
$qry = sql_query($sql);
while ($row = sql_fetch_array($qry)) {
    $cash = $row[mi_cash];
    $is_extend = false;
    $sq2 = " select * from $mw_cash[membership_log_table] where mb_id = '$member[mb_id]' and ml_edate > '$g4[time_ymdhis]' and ms_id = '$row[ms_id]' ";
    $ro2 = sql_fetch($sq2);
    if ($ro2 && $row[mi_cash_extend]) {
        $cash *= (100-$row[mi_cash_extend])/100;
        $is_extend = true;
    }
*/
for ($i=0, $m=count($list); $i<$m; $i++) {
    $row = $list[$i];
    $cash = $row[cash];
    $is_extend = $row[is_extend];
    $is_join_sale = $row[is_join_sale];
    $is_new = $row[is_new];
?>
<tr>
    <? if ($list[$i-1][ms_id] != $list[$i][ms_id]) { ?>
    <td class="tls" rowspan="<?=$rows[$list[$i][ms_id]]?>">
        <strong><?=$row[ms_name]?></strong>
    </td>
    <? } ?>
    <td class="tls">
        <input type="checkbox" name="mi_id[]" class="mi_id" value="<?=$row[mi_id]?>" ms_id="<?=$row[ms_id]?>" cash="<?=$cash?>" cost="<?=$row[mi_cash]?>"
        <? if ($list[$i-1][ms_id] != $list[$i][ms_id]) echo "checked"; ?>>
        <?=$row[mi_day]?> 일</strong>
        <!--<span class="i"><? if ($is_extend) { ?> (<?=substr($row[ml_edate], 0, 10)?> 종료) <? } else { ?> (신규) <? } ?> </span>-->
    </td>
    <td class="tls">
        <?=$mw_cash[cf_cash_name]?> <?=$cash?> <?=$mw_cash[cf_cash_unit]?>

    </td>
    <td class="tls">
        <? if ($is_extend) { ?>
            <? if ($row[mi_cash_extend]) { ?>
            <s><?=$mw_cash[cf_cash_name]?> <?=$row[mi_cash]?> <?=$mw_cash[cf_cash_unit]?></s>
            연장 <?=$row[mi_cash_extend]?>% 할인
            <? } else { ?>
            연장
            <? } ?>
        <? } else if ($is_join_sale) { ?>
            <? if ($row[mi_cash_join_sale]) { ?>
            <s><?=$mw_cash[cf_cash_name]?> <?=$row[mi_cash]?> <?=$mw_cash[cf_cash_unit]?></s>
            장기회원 <?=$row[mi_cash_join_sale]?>% 할인
            <? } ?>
        <? } else {?>
            <? if ($is_new == 'new') { ?>
            신규
            <? } else if ($is_new == 're') {?>
            재가입
            <? } ?>
        <? } ?>
    </td>
    <td class="tls right">
        <?=number_format(mw_cash_to_payment($cash, $mw_cash[cf_tax]))?> 원 &nbsp;
    </td>
</tr>
<? } ?>
</table>
<!--<div class="i">※  다운로드 한 프로그램은 기간에 관계없이 사용하실 수 있습니다.</div>-->

<!--
<h3>사용 홈페이지</h3>
<table border="0" cellpadding="0" cellspacing="0" class="t">
<colgroup width="100"/>
<colgroup width="350"/>
<colgroup width="250"/>
<tr>
    <td class="tt">소유자</td>
    <td class="tt">도메인</td>
    <td class="tt">결제금액</td>
</tr>
<?// for ($i=0; $i<5; $i++) {?>
<tr>
    <td class="tls">
        <select name="domain_own[]" class="domain_own" number="<?=$i?>">
            <option value=""> </option>
            <option value="oneself">본인</option>
            <option value="other">타인</option>
        </select>
    </td>
    <td class="tls">
        <input type="text" size="50" class="ed" name="domain_url">
    </td>
    <td class="tls">
        <div id="domain_price_<?=$i?>">-</div>
    </td>
</tr>
<? //} ?>
</table>
<div class="i">※  본인명의 홈페이지 정의 : 도메인 명의 = 홈페이지 대표자 명의 = 마이위트 아이디 명의 (삼위일체) </div>
<div class="i">※  가입 후 라이센스센터에서 추가등록 가능합니다. </div>
-->

<div id="cash_info">
필요한 <?=$mw_cash[cf_cash_name]?> : <span id="total_cash" class="cash">0</span> <?=$mw_cash[cf_cash_unit]?> /
나의 <?=$mw_cash[cf_cash_name]?> : <span class="cash"><?=number_format($mw_cash[mb_cash])?></span> <?=$mw_cash[cf_cash_unit]?> /
추가 결제 <?=$mw_cash[cf_cash_name]?> : <span id="payment_cash" class="cash">0</span> <?=$mw_cash[cf_cash_unit]?>
</div>

<div id="payment_info">
    총 결제금액 :  <span id="total_payment" class="cash">0</span> 원
</div>

<div id="payment_buttons">
<? if (1) { ?><img src="<?=$mw_cash[path]?>/img/bt_join.png" class="btn-image" onclick="cash_membership_charge('cash')"><? } ?>
<? if ($mw_cash[cf_card]) { ?><img src="<?=$mw_cash[path]?>/img/bt_card.gif" class="btn-image" onclick="cash_membership_charge('card')"><? } ?>
<? if ($mw_cash[cf_bank]) { ?><img src="<?=$mw_cash[path]?>/img/bt_bank.gif" class="btn-image" onclick="cash_membership_charge('bank')"><? } ?>
<? if ($mw_cash[cf_hp]) { ?><img src="<?=$mw_cash[path]?>/img/bt_hp.gif" class="btn-image" onclick="cash_membership_charge('hp')"><? } ?>
<? if ($mw_cash[cf_account]) { ?><img src="<?=$mw_cash[path]?>/img/bt_account.gif" class="btn-image" onclick="account_move()"><? } ?>
<? if ($mw_cash[cf_paypal]) { ?><img src="<?=$mw_cash[path]?>/img/bt_paypal.png" class="btn-image" onclick="cash_membership_charge('paypal')"><? } ?>
</div>

</form>

<? echo $mw_cash[cf_membership_tail]; ?>

</div> <!-- box -->

<script type="text/javascript" src="<?=$mw_cash[path]?>/cybercash.js"></script>
<script type="text/javascript">
var total_cash = 0;
var total_cost = 0;
var total_site = 0;
var total_payment = 0;
var payment_cash = 0;
var cash_name = "<?=$mw_cash[cf_cash_name]?>";
var cash_unit = "<?=$mw_cash[cf_cash_unit]?>";

$(document).ready(function () {
    self.resizeTo(780,500); 
    window.moveTo(
        (screen.availWidth - 780) / 2,
        (screen.availHeight - 500) / 2
    );

    $(".mi_id").click(function () {
        check_item($(this));
        set_total_cash();
    });
    $(".domain_own").change(set_total_cash);
    set_total_cash();
});

function all_check(obj)
{
    old = null;
    $('.mi_id').each(function () {
        $(this).attr('checked', obj.checked);
        if (old && $(this).attr("ms_id") == $(old).attr("ms_id")) {
            $(this).removeAttr("checked");
        }
        old = $(this);
    });
}

function check_item(obj)
{
    var checked = $(obj).attr("checked");
    $(".mi_id").each(function () {
        if ($(this).attr("ms_id") == $(obj).attr("ms_id")) {
            $(this).removeAttr("checked");
        }
    });
    if (checked == true)
        $(obj).attr("checked", "checked");
    else
        $(obj).removeAttr("checked");
}

function set_total_cash()
{
    total_cash = 0;
    total_cost = 0;
    total_site = 0;
    $(".mi_id").each(function () {
        cash = Number($(this).attr("cash"));
        cost = Number($(this).attr("cost"));
        if ($(this).is(":checked")) {
            total_cash += cash;
            total_cost += cost;
        }
    });
/*
    $(".domain_own").each(function (i, v) {
        if ($(this).val() == "oneself") {
            $("#domain_price_"+i).text("무료");
        } else if ($(this).val() == "other") {
            $("#domain_price_"+i).text(cash_name + " " + total_cost + " " + cash_unit);
            total_site++;
        }
    });
    total_cash += total_cost * total_site; 
*/

    payment_cash = Number(total_cash) - <?=$mw_cash[mb_cash]?>;
    if (payment_cash < 0)
        payment_cash = 0;

    fwrite.ac_cash.value = payment_cash;

    total_payment = cash_to_payment(payment_cash);

    total_cash = number_format(String(total_cash));
    payment_cash = number_format(String(payment_cash));
    total_payment = number_format(String(total_payment));

    $("#total_cash").text(total_cash);
    $("#payment_cash").text(payment_cash);
    $("#total_payment").text(total_payment);
}

// 캐쉬->결제금액 계산
function cash_to_payment(cash)
{
    var tax = '<?=$mw_cash[cf_tax]?>';
    if (tax) { // 부가세 별도
	cash_price = parseFloat(<?=$mw_cash[cf_cash_price]?> * 1.1).toFixed(0);
	payment = cash * cash_price;
    } else {
	payment = cash * <?=$mw_cash[cf_cash_price]?>;
    }
    return payment;
}

// 결제금액->캐쉬 계산
function payment_to_cash($payment)
{
    var tax = '<?=$mw_cash[cf_tax]?>';
    if (tax) { // 부가세 별도
	cash_price = <?=$mw_cash[cf_cash_price]?> * 1.1;
	cash = payment / cash_price;
    } else {
	cash = payment / <?=$mw_cash[cf_cash_price]?>;
    }
    return cash;
}

function account_move() {
    var msg = "";
    msg += "무통장 입금은 관리자 확인이 필요하기 때문에 바로결제가 지원되지 않습니다.\n\n";
    msg += "<?=$mw_cash[cf_cash_name]?> 충전후 다시 가입신청 해주시기 바랍니다.\n\n";
    msg += "<?=$mw_cash[cf_cash_name]?> 충전 페이지로 이동하시겠습니까?";
    if (!confirm(msg)) return;

    window.open("<?=$mw_cash[path]?>");
    self.close();
}

function cash_membership_charge(paytype) {
    if (!confirm('결제하시겠습니까?')) return false;
    if (paytype == 'cash')
        fwrite.action = "buy-membership-update.php";
    else
        fwrite.action = "cash-charge-update.php";

    fwrite.paytype.value = paytype;
    fwrite.submit();
}
</script>
<?
include_once("$g4[path]/tail.sub.php");
